package mvc.controller;

import mvc.model.pojos.UserBean;
import mvc.model.service.SignService;
import mvc.model.service.UserService;
import mvc.model.service.impl.SignServiceImpl;
import mvc.model.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "SignServlet", urlPatterns = "/sign")

public class SignServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname = request.getParameter("uname");
        System.out.println(uname);
        SignService signService = new SignServiceImpl();
        UserService userService = new UserServiceImpl();
        UserBean userBean = userService.queryOne(uname);
        boolean flag = signService.checkUname(uname);
        if (flag) {
            signService.addUser(uname);
            Cookie name = new Cookie("uname", userBean.getUname());
            Cookie pass = new Cookie("upass", userBean.getUpass());
            response.addCookie(name);
            response.addCookie(pass);
            response.getWriter().append("ok");
            request.getSession().setAttribute("user", userBean);
        } else {
            response.getWriter().append(null);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        if (request.getSession().getAttribute("user") != null) {
            response.sendRedirect("center");
        } else {
            response.sendRedirect("sign.jsp");
        }
    }
}
